<!-- add ： 选择用户时，可以更具用户标签来。 2023年12月29日 -->
<template>
  <el-card class="mark-setting" shadow="never">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="100">
      <el-form-item label="考试用户：" prop="examUserIds">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input
              @change="getUserList"
              v-model="search.searchName"
              placeholder="请输入机构名称或用户名称进行筛选"
          /></el-col>
          <el-col :span="7">
            <el-select
              @change="getUserList"
              v-model="search.searchLabel"
              placeholder="请选择标签"
            >
              <el-option
                v-for="item in labels"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              /> </el-select
          ></el-col>
          <el-col :span="24">
            <el-space style="margin-top: 20px">
              <el-button type="primary" @click="getUserList">搜索</el-button>
              <el-button type="primary" @click="reset">重置</el-button>
            </el-space>
          </el-col>

          <el-col :span="24">
            <el-table
              :row-key="getRowKeys"
              :max-height="300"
              border
              stripe
              ref="multipleTableRef"
              :data="tableData"
              style="width: 100%; margin-top: 20px"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
                :reserve-selection="true"
              />

              <el-table-column property="loginName" label="身份证号">
              </el-table-column>

              <el-table-column property="name" label="姓名" />

              <el-table-column property="phone" label="手机号" />

              <el-table-column property="orgName" label="机构" />

              <el-table-column property="labelName" label="标签">
              </el-table-column>
              <el-table-column property="sex" label="性别"> </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="7">
            <el-pagination
              style="margin-top: 20px"
              v-model:current-page="search.curPage"
              v-model:page-size="search.pageSize"
              background
              :page-sizes="[50, 100, 200, 500]"
              small
              @size-change="getUserList"
              @current-change="getUserList"
              layout="prev, pager, next, jumper, ->, total"
              :total="total"
            /> </el-col
          ><el-col :span="10">
            <div style="margin-top: 20px; color: #606266; font-size: 12px">
              当前已选考试用户数目
              <span style="color: #c45656;font-size: 14px"> {{ examUsers.length }} </span>
            </div>
          </el-col></el-row
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";

import type { FormInstance, FormRules } from "element-plus";
import { useExamStore } from "@/stores/exam";
/* import Select from "@/components/Select.vue"; */
import http from "@/request";

/* add：选择用户可以通过标签搜索: 2023年12月29日 */
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  /*  	console.log("val", val);  */
  multipleSelection.value = val;
  /* 	console.log(multipleSelection.value); */
  /* for (let index = 0; index < val.length; index++) {
		const element = val[index];
	        console.log("element", element.id);
		examUsers.value.push(element.id);
	} */
  examUsers.value = val ? val.map((item) => item.id) : [];
  form.examUserIds = examUsers.value;
  /* 	console.log("examUsers", examUsers.value); */
  /* examUsers.value = multipleSelection.value; */
};

const reset = () => {
  search.value = {
    searchName: "",
    searchLabel: "",
    curPage: 1,
    pageSize: 50,
  };
  getUserList();
};
const labels = ref([]);

const search = ref({
  searchName: "",
  searchLabel: "",
  curPage: 1,
  pageSize: 50,
});
const total = ref(0);
const tableData = ref([]);
/* let curPage = 1;
let pageSize = 100; */
const getUserList = async () => {
  try {
    const res = await http.post("user/listpage", {
      /* 		ids: form.examUserIds.join(), */
      label_id: search.value.searchLabel,
      name: search.value.searchName,
      curPage: search.value.curPage,
      pageSize: search.value.pageSize,
    });
    /* 	console.log(res.data.data.total);
		console.log(res.data.data.list); */
    tableData.value = res.data.data.list;
    total.value = res.data.data.total;
  } catch (error) {
    console.log(error);
  }
};

const getLabels = async () => {
  try {
    const res = await http.post("label/listpage", {
      curPage: 1,
      pageSize: 10,
    });
    /* console.log(res.data.data.total);
		console.log(res.data.data.list); */
    labels.value = res.data.data.list;
  } catch (error) {
    console.log(error);
  }
};
// 定义变量
defineExpose({ next });
const form = useExamStore(); // 表单
const formRef = ref<FormInstance>(); // 表单引用
const formRules = reactive<FormRules>({
  // 表单校验规则
  /* examUserIds: [
		{ required: true, message: "请选择考试用户", trigger: "blur" },
	], */
});

const examUsers = ref([] as any[]); // 考试用户
// 默认选中数据
const getRowKeys = (row) => {
  return row.id;
};
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const selectFormStore = async () => {
  /* 	console.log("selectFormStore", form.examUserIds); */
  if (form.examUserIds.length > 0) {
    /* console.log("examUserIds", form.examUserIds.includes(99)); */
    // 根据已选id获取完整row
    /* 	await getUserList();  */
    // console.log("tableData.value", tableData.value);
    let rows = tableData.value.filter((item) => {
      return form.examUserIds.includes(item.id);
    });
    // console.log("rows", rows);
    if (rows) {
      rows.forEach((i) => {
        multipleTableRef.value!.toggleRowSelection(i, true);
      });
    }
  }
};
nextTick(() => {
  // console.log("nextTick", form.examUserIds);
});
// 组件挂载完成后，执行如下方法
onMounted(async () => {
  await getUserList();
  await getLabels();
  await selectFormStore();
});

// 下一步
async function next() {
  if (examUsers.value.length == 0) {
    ElMessage({
      message: "请选择考试用户",
      type: "error",
    });
    return false;
  }
  if (!formRef.value) return false;
  return await formRef.value.validate((valid, fields) => {
    return valid;
  });
}
</script>

<style lang="scss" scoped>
.mark-setting {
  flex: 1;
  overflow: visible;
  .el-alert {
    padding: 0;
    height: 24px;
  }
}
</style>
